<template>
  <el-form
    style="margin: 20px 0"
    :model="formData"
    ref="ruleForm"
    :label-width="labelWidth"
  >
    <template v-for="field in fields" :key="field.value">
      <slot v-if="field.allSlot" :name="field.value" :item="formData"></slot>
      <el-form-item
        v-else
        :label="field.label"
        :prop="field.value"
        :label-width="field.width"
      >
        <slot v-if="field.slot" :name="field.value" :item="formData"></slot>
        <component
          v-else
          :is="field.type || 'el-input'"
          v-bind="field.props"
          v-model="formData[field.value]"
          style="width: 100%"
        >
          <template v-if="field.type === 'el-select'">
            <el-option
              v-for="item in field.props.options"
              :key="item[field.props.valueKey] || item.value"
              :label="item[field.props.labelKey] || item.label"
              :value="item[field.props.valueKey] || item.value"
            />
          </template>
        </component>
      </el-form-item>
    </template>

    <el-form-item>
      <slot v-if="hasFooterSlot" name="footer" :data="formData"></slot>
      <template v-else>
        <el-button type="primary" @click="onSubmit">确定</el-button>
        <el-button @click="cancel">取消</el-button>
      </template>
    </el-form-item>
  </el-form>
</template>

<script lang='ts'>
import { deepClone } from '@/utils'
import { computed, defineComponent, ref, watchEffect } from '@vue/runtime-core'

export default defineComponent({
  name: 'BaseForm',
  props: {
    fields: {
      type: Array,
      default: () => [],
    },
    data: {
      type: Object,
      default: () => ({}),
    },
    rules: {
      type: Object,
      default: () => ({}),
    },
    labelWidth: {
      type: String,
      default: '100px',
    },
  },
  emits: ['cancel', 'submit'],
  setup (props, { emit, slots }) {
    console.log('base form', props)
    const formData = ref({})
    const ruleForm = ref(null)

    // formData.value = deepClone(props.data)
    // watch(
    //   () => props.data,
    //   (value) => {
    //     formData.value = deepClone(value)
    //   },
    //   { deep: true },
    // )
    watchEffect(() => {
      formData.value = deepClone(props.data)
    })

    const hasFooterSlot = computed(() => !!slots.footer)
    function onSubmit () {
      emit('submit', formData.value)
      console.log('formData', formData.value)
    }
    function cancel () {
      ruleForm.value.resetFields()
      emit('cancel')
    }
    return {
      ruleForm,
      formData,
      hasFooterSlot,
      onSubmit,
      cancel,
    }
  },
})
</script>

<style scoped lang="less">
</style>
